package com.bingo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bingo.common.CommunityUtil;
import com.bingo.common.R;
import com.bingo.entity.User;
import com.bingo.entity.dto.MyIntegers;
import com.bingo.entity.dto.req.CheckUser;
import com.bingo.service.UserService;
import com.bingo.until.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Bingo
 * @version 1.0
 * @description 用户控制类
 * @date 2024/3/26 22:07
 */

@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    //cookie存储的位置
    @Value("${server.servlet.context-path}")
    private String contextPath;

    private RedisTemplate redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    //校验密码
    @PostMapping("/checkPassword")
    public R checkPassword(@RequestBody CheckUser checkUser) {
        if (userService.checkPassword(checkUser.getUserNo(), checkUser.getPassword())){
            return R.success("登录成功");
        }else {
            return R.error("用户名或密码错误");
        }
    }

    /**
     * 后台登录
     * @param user   用户的账号和密码
     * @param response
     * @return 返回该账号信息
     */
    @PostMapping("login/{type}")
    public R<User> login(@RequestBody CheckUser user,@PathVariable("type") int type,HttpServletResponse response, HttpServletRequest request ){

        if(user.getUserNo() == null || user.getUserNo().equals("")){
            // 从cookie中获取凭证
            String token = CookieUtil.getValue(request, "token");
            //根据凭证从redis中获取对应用户
            User loginUser = (User) redisTemplate.opsForValue().get("token:" + token);
            if (loginUser == null) {
                System.out.println(R.error("未登录或token已过期"));
                return R.error("未登录或token已过期");

            }
            loginUser.setPassword(null);
            return R.success(loginUser);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId,user.getUserNo());
        User search = userService.getOne(queryWrapper);
        if (search==null){
            return R.error("账号或密码错误！");
        }
        if (!search.getPassword().equals(user.getPassword())){
            return R.error("账号或密码错误！");
        }

        if (type==0 && search.getType() == 2) {
            return R.error("权限不足,场长不可登录后台！");
        }
        if (type==1 && (search.getType() == 0 || search.getType()==1)){
            return R.error("权限不足,管理员不可登录小程序！");
        }

        search.setPassword(null);
        String token = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("token",token);
        cookie.setPath(contextPath);
        //让浏览器保存token一周
        cookie.setMaxAge(60*60*24*7);
        response.addCookie(cookie);
        redisTemplate.opsForValue().set("token:"+token,search, 60*60*24*7, TimeUnit.SECONDS);
        R<User> r = R.success(search);
        r.setStatusText("登录成功！");
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
        r.setMap(map);

        return r;
    }


    //退出登录
    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request){
        //先把redis中的保存信息清理了
        String token = CookieUtil.getValue(request, "token");
        redisTemplate.delete("token:"+token);
        return R.success("退出成功");
    }

    /**
     * 注册
     * @param user  用户的信息
     * @param code  邮箱发送的验证码
     * @return
     */
    @PostMapping("register")
    public R<String> register(@RequestBody User user){
        boolean register = userService.register(user);
        if (!register){
            return R.error("注册失败");
        }
        //注册
        return R.success("注册成功");
    }

    /**
     * 更新用户信息
     * @param user  用户的信息
     * @return
     */
    @PostMapping("update")
    public R<String> update(@RequestBody User user){
        boolean update = userService.updateUser(user);
        if (!update){
            return R.error("更新失败");
        }
        //更新
        return R.success("更新成功");
    }

    /**
     * 删除用户
     * @param userNo  用户的账号
     * @return
     */
    @PostMapping("delete/{userNo}")
    public R<String> delete(@PathVariable String userNo){
        //后续改为逻辑删除
        boolean delete = userService.deleteUser(userNo);
        if (!delete){
            return R.error("删除失败");
        }
        //删除成功
        return R.success("删除成功");
    }

    /**
     * 获取全部用户
     * @return
     */
    @PostMapping("all")
    public R getAllUser(@RequestBody MyIntegers myIntegers){

        //判断是否筛选用户类型
        Integer[] types = null;
        if (myIntegers==null||myIntegers.getTypes()==null){

        }else {
            types = myIntegers.getTypes();
        }


        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (types!=null && types.length>0){
            wrapper.in("type",types);
        }
        List<User> list = userService.list(wrapper);
        //去除密码
        for (User user : list) {
            user.setPassword(null);
        }
        return R.success(list);
    }

    /**
     * 修改密码
     * @param userNo  用户的账号
     * @return
     */
    @PostMapping("updatePassword")
    public R updatePassword(@RequestBody CheckUser user){
        boolean update = userService.updatePassword(user);
        if (!update){
            return R.error("修改失败！");
        }
        //修改成功
        return R.success("修改成功！");
    }


}
